package com.mifengs.mall.ui.write;


import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.entity.ImageUpload;
import com.mifengs.mall.netWork.NetWork;

import java.io.File;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lynn on 2018/3/12.
 */

public class HandWritePresent implements HandWriteContract.Presenter {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private HandWriteContract.View mView;

    public HandWritePresent(HandWriteContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void upLoadImg(List<String> mImgUrls) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <mImgUrls.size() ; i++) {
            File f=new File(mImgUrls.get(i));
            if (f!=null) {
                builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
        builder.addFormDataPart("attachmentType","SIGNATURE");
        List<MultipartBody.Part> parts = builder.build().parts();
        mView.showLoading();
        NetWork.getImageUploadApi().uploadFiles(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ImageUpload>bindToLife())
                .subscribe(new Observer<ImageUpload>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(ImageUpload imageUpload) {
                        mView.hideLoading();
                        if(imageUpload.getMsg().equals("OK") && imageUpload.getStatus().equals("1")){
                                System.out.println("上传照片成功：url = " + imageUpload.getResult().getPic());
                            mView.toFinish(imageUpload.getResult().getPic());
                        }
                    }
                });

    }
}
